//
//  VideoDownloadDelegate.swift
//  TestConcurreces
//
//  Created by rolodestar on 2025/6/16.
//

import Foundation
import SwiftData

@available(macOS 14,iOS 17, *)
public final class VideoDownloadDelegate: NSObject,URLSessionDownloadDelegate{
    var storedFolder: URL{
        let url =   FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let result =  url.appending(path: "RoDownload") //.appendingPathComponent("RoDownload", conformingTo: .directory) //.appendPathComponent("RoDownload")
        try! FileManager.default.createDirectory(at: result, withIntermediateDirectories: true)
        return result
    }
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)  {
        let id = UUID()
        let tmpFilePath = storedFolder.appending(path:"\(id.uuidString).mp4")
        do{
            try FileManager.default.copyItem(at: location, to: tmpFilePath)
        }catch{
            print(error)
        }
        Task{
            
            viewThread(at: "delegate - finished download -")
            guard let httpResponse = downloadTask.response as? HTTPURLResponse ,(200..<300).contains(httpResponse.statusCode)  ,let response = downloadTask.response else{
                print("response error")
                return
            }
            let fileName = response.suggestedFilename ?? "\(id.uuidString).mp4"
            
            let filePath = await actor.storedFolder.appending(path: fileName)//, conformingTo: .video)
            if await !actor.checkIsDownload(filePath: filePath){
                do{
                    guard FileManager.default.fileExists(atPath: tmpFilePath.path()) else {
                        print("临时文件不存在！需重新下载或检查下载逻辑\n\(tmpFilePath.path())")
                        return
                    }
                    try FileManager.default.moveItem(at: tmpFilePath, to: filePath)
                }catch{
                    print(error)
                }
            }
            try await actor.update(id: videoId, localPath: filePath)
            
        }
    }
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        Task{
            let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
            try await actor.update(id: videoId, progress: progress)
        }
    }
    private let videoId: PersistentIdentifier
    private let actor: VideoActor
    init(actor: VideoActor,videoId: PersistentIdentifier) {
        self.actor = actor
        self.videoId = videoId
    }
    
//    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
//        <#code#>
//    }
    
}
